<template>
  <div>
    <el-card>
      <div class="flex justify-between mb-4">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索分类"
          style="width: 200px"
          @input="fetchCategories"
        />
        <el-button type="primary" @click="openForm()">新增分类</el-button>
      </div>

      <el-table :data="filteredCategories" border style="width: 100%">
        <el-table-column label="ID" prop="id" width="80" />
        <el-table-column label="名称" prop="name" />
        <el-table-column label="操作" width="180">
          <template #default="{ row }">
            <el-button size="small" @click="openForm(row)">编辑</el-button>
            <el-button size="small" type="danger" @click="remove(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 弹窗表单 -->
    <el-dialog v-model="dialogVisible" :title="form.id ? '编辑分类' : '新增分类'">
      <el-form :model="form" label-width="80px" :rules="rules" ref="formRef">
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  getCategories,
  createCategory,
  updateCategory,
  deleteCategory
} from '@/api/categories'

const categories = ref([])
const searchKeyword = ref('')
const dialogVisible = ref(false)
const formRef = ref()
const form = ref({ id: null, name: '' })
const rules = { name: [{ required: true, message: '请输入分类名称', trigger: 'blur' }] }

const fetchCategories = async () => {
  categories.value = (await getCategories()).data;
}

const filteredCategories = computed(() => {
  if (!searchKeyword.value) return categories.value
  return categories.value.filter(c =>
    c.name.toLowerCase().includes(searchKeyword.value.toLowerCase())
  )
})

const openForm = (item = null) => {
  form.value = item ? { ...item } : { id: null, name: '' }
  dialogVisible.value = true
}

const submitForm = async () => {
  await formRef.value.validate()
  const isEdit = !!form.value.id
  if (isEdit) {
    await updateCategory(form.value)
    ElMessage.success('修改成功')
  } else {
    await createCategory(form.value)
    ElMessage.success('创建成功')
  }
  dialogVisible.value = false
  fetchCategories()
}

const remove = async (id) => {
  await ElMessageBox.confirm('确认删除该分类吗？', '提示', { type: 'warning' })
  await deleteCategory(id)
  ElMessage.success('删除成功')
  fetchCategories()
}

onMounted(fetchCategories)
</script>

<style scoped>
.mb-4 {
  margin-bottom: 16px;
}
</style>
